
import * as THREE from 'three';

class GLTFExporter {
    constructor() {
        this.threeExporter = null;
        this.loadExporter();
    }

    async loadExporter() {
        // 动态导入Three.js的GLTFExporter
        try {
            const module = await import('three/examples/jsm/exporters/GLTFExporter.js');
            this.threeExporter = new module.GLTFExporter();
        } catch (error) {
            console.error('无法加载GLTFExporter:', error);
        }
    }

    async parse(scene, options = {}) {
        if (!this.threeExporter) {
            await this.loadExporter();
            if (!this.threeExporter) {
                throw new Error('GLTFExporter未能加载，请确保已安装three库');
            }
        }

        return new Promise((resolve, reject) => {
            try {
                this.threeExporter.parse(scene, (result) => {
                    resolve(result);
                },
                    (error) => {
                        reject(error);
                    },
                    options);
            } catch (error) {
                reject(error);
            }
        });
    }

    // 辅助方法：将模型数据转换为GLB
    static createGLBFromJSON(result) {
        // 检查结果是否为二进制GLB
        if (result instanceof ArrayBuffer) {
            return result;
        }

        // 如果是JSON，需要转换
        const jsonString = JSON.stringify(result);
        const jsonChunk = new TextEncoder().encode(jsonString);
        const jsonChunkPrefix = new Uint32Array([
            jsonChunk.byteLength, // chunk长度
            0x4E4F534A // 'JSON'的ASCII码
        ]);

        // 创建GLB
        const glbData = new Uint8Array(
            12 + // GLB header
            8 + // JSON chunk header
            jsonChunk.byteLength
        );

        // 写入GLB头
        const glbHeader = new Uint32Array(glbData.buffer, 0, 3);
        glbHeader[0] = 0x46546C67; // 'glTF'的ASCII码
        glbHeader[1] = 2; // 版本
        glbHeader[2] = 12 + 8 + jsonChunk.byteLength; // 文件长度

        // 写入JSON chunk头
        const chunkHeader = new Uint32Array(glbData.buffer, 12, 2);
        chunkHeader[0] = jsonChunk.byteLength;
        chunkHeader[1] = 0x4E4F534A; // 'JSON'的ASCII码

        // 写入JSON数据
        glbData.set(jsonChunk, 20);

        return glbData.buffer;
    }
}

export { GLTFExporter }; 